﻿using System;
using BlogApp.Data.Models;
using BlogApp.Data.Service;
using BlogApp.WP8.Utils;
using GalaSoft.MvvmLight.Command;
using Microsoft.Practices.ServiceLocation;

namespace BlogApp.WP8.ViewModel
{
    public class PostViewModel : DataViewModel
    {
        public RelayCommand<Post> OpenBlogPostCommand;
        public RelayCommand<Post> SavePostOfflineCommand;
        public RelayCommand<Post> RemovePostOfflineCommand;
        public NavigateCommand NavigateCommand { get; private set; }


        private Post _selectedBlogPost;
        public Post SelectedBlogPost
        {
            get { return _selectedBlogPost; }
            set { _selectedBlogPost = value; RaisePropertyChanged("SelectedBlogPost"); }
        }

        public PostViewModel()
        {
            OpenBlogPostCommand = new RelayCommand<Post>(openBlogPost);
            SavePostOfflineCommand = new RelayCommand<Post>(savePostOffline);
            RemovePostOfflineCommand = new RelayCommand<Post>(removePostOffline);
            NavigateCommand = new NavigateCommand();
        }

        private async void removePostOffline(Post blogPost)
        {

            IsLoading = true;

            try
            {
                await DataService.Instance.RemoveOffline(blogPost);
                ServiceLocator.Current.GetInstance<MainViewModel>().LoadOfflinePosts.Execute(null);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            
            IsLoading = false;
        }


        private void openBlogPost(Post blogPost)
        {
            SelectedBlogPost = blogPost;
            NavigateCommand.Execute("/View/PostDetailPage.xaml");
        }

        private async void savePostOffline(Post blogPost)
        {
            IsLoading = true;
            await DataService.Instance.SaveOffline(blogPost);
            ServiceLocator.Current.GetInstance<MainViewModel>().LoadOfflinePosts.Execute(null);
            SelectedBlogPost.IsOffline = true;

            IsLoading = false;
        }
    }
}